<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>HideAndSeek</title>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <link rel="icon" href="data:;base64,=">
</head>
<body>
<div id="app">
    <label>
        玩家ID：
        <input type="text" :value="playerId">
    </label>
    <button @click="matchPlayer">匹配</button>
    <div v-if="matching" style="display: inline">
        匹配中。。。。。。
    </div>
</div>

</body>
</html>

<script>
    var app = new Vue({
        el: '#app',
        data: {
            playerId: 'player_' + Math.round(Math.random() * 1000),
            websock: null,
            roomId: '',
            matching: false
        },
        created() {
            this.initWebSocket();
        },
        destroyed() {
            this.websock.close() //离开路由之后断开websocket连接
        },
        methods: {
            //匹配玩家
            matchPlayer() {
                let actions = {
                    'code': 600
                };
                this.websocketSend(actions);
                this.matching = true;
            },
            startRoom() {
                let actions = {
                    'code': 601,
                    'room_id': this.roomId
                };
                this.websocketSend(actions);
                this.matching = false;
            },
            initWebSocket() {
                const wsUri = "ws://139.199.64.182:9502?player_id=" + this.playerId;
                this.websock = new WebSocket(wsUri);
                this.websock.onmessage = this.websocketOnMessage;
                this.websock.onopen = this.websocketOnOpen;
                this.websock.onerror = this.websocketOnError;
                this.websock.onclose = this.websocketClose;

            },
            websocketOnOpen() {
                let actions = {
                    'test': '123456'
                };
                this.websocketSend(actions)

            },
            websocketOnError() {//失败重连
                this.initWebSocket()
            },
            websocketOnMessage(e) {//数据接收
                let message = JSON.parse(e.data);
                let responseData = message.data;
                switch (message.code) {
                    case 1001://匹配成功
                        this.roomId = responseData.room_id;
                        this.startRoom();
                        break;
                }
            },
            websocketSend(data) {//数据发送
                this.websock.send(JSON.stringify(data))
            },
            websocketClose(e) {//关闭
                console.log('断开连接', e)
            }
        }
    })
</script>
